# -*- coding: utf-8 -*-
import logging
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from requests.adapters import HTTPAdapter

# 出错时,重试2次,一共执行3次
request = requests.Session()
request.mount('http://', HTTPAdapter(max_retries=2))
request.mount('https://', HTTPAdapter(max_retries=2))


# 待检测的网址,仅支持GET请求
urls = ["https://www.baidu.com","http://www.mtain.top"]
# 接收短信通知的手机号码
phone = "180000000"

# 阿里云短信接口相关信息
accessKeyId = 'xxxx'
accessSecret = 'xxxx'
signName = 'xxxxx'
templateCode = 'SMS_xxxx'
logger = logging.getLogger()

def handler(event, context):
  for url in urls:
    do_httpchk(url)

def do_httpchk(url):
  logger.info('检测网站:{}'.format(url))
  try:
    req = request.get(url, timeout=5)
    logger.info('网站:{}响应正常,返回数据长度:{}'.format(url,len(req.text)))
  except Exception as e:
    logger.error('网站:{}服务异常,{}'.format(url,e))
    send_sms(url)
    
def send_sms(url):
  client = AcsClient(accessKeyId, accessSecret, 'default')
  request = CommonRequest()
  request.set_accept_format('json')
  request.set_domain('dysmsapi.aliyuncs.com')
  request.set_method('POST')
  request.set_protocol_type('https') # https | http
  request.set_version('2017-05-25')
  request.set_action_name('SendSms')
    
  request.add_query_param('PhoneNumbers', phone)
  request.add_query_param('SignName', signName)
  request.add_query_param('TemplateCode', templateCode)
  # 阿里云短信变量 [a-zA-Z0-9] 且 长度小于20
  web_name = url.replace('https://','').replace('http://','').replace('.','-')[0:18]
  request.add_query_param('TemplateParam', '{"code":"'+web_name+'"}')
  
  response = client.do_action(request)
  logger.info('Send SMS Response:'+str(response, encoding = 'utf-8'))